from retrying import retry
import requests
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
from mySpiders.settings import headers


@retry(stop_max_attempt_number=5)
def parse_img_url(url):
    resp = requests.get(url, headers=headers, timeout=30, verify=False)
    return resp.content


def save_img(item):
    spider_name = item['name']
    SKU_ID = item['SKU_ID']
    img_url = item['img_url']
    print(SKU_ID, img_url)
    if SKU_ID and img_url:
        path_img = "images/{}/{}.jpg".format(spider_name, SKU_ID)
        path_img = os.path.join(BASE_DIR, path_img)
        html_img = parse_img_url(img_url)
        with open(path_img, 'wb') as file:
            file.write(html_img)